#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import MySQLdb
import time
import os

file=sys.argv[1]
host=sys.argv[2]
port=sys.argv[3]
user=sys.argv[4]
password=sys.argv[5]
db=sys.argv[6]
day=sys.argv[7]

def format_float(a):
    if a:
        return round(float(a),2)

if os.path.exists(file):
    conn = MySQLdb.connect(host,user,password,db)
    cursor = conn.cursor()
    cursor.execute("SET NAMES utf8")
    columns='cid,sid,day,geographicalName,geographicalType,pv,uv,ip,bounce,averageAccessTime,session,conversions,update_time'
    columns_info={'cid':'str','sid':'str','day':'int','geographicalName':'str','geographicalType':'int','pv':'long','uv':'long','ip':'str','bounce':'long','averageAccessTime':'format_float','session':'long','update_time':'int','conversions':'long'}
    c_l=columns.strip().split(',')
    args=','.join(['%s' % i for i in c_l])
    args2=','.join(['%s' for i in c_l])
    lines=[]
    update_time = int(time.time())
    with open(file) as f:
        for i in f:
            l=i.rstrip('\n').split('\001')
            if l[0] and l[1]:
                l.append(update_time)
                lines.append(tuple([eval("%s('''%s''')" % (columns_info[c_l[index]],j if j else '0')) for index,j in enumerate(l)]))
    if len(lines)>0:
        sql='insert into nas_visitor_area(%s) values(%s)' % (args,args2)
        cursor.executemany(sql,tuple(lines))
        conn.commit()
        delete_sql="delete from nas_visitor_area where day='%s' and update_time!=%s" % (day,update_time)
        cursor.execute(delete_sql)
        conn.commit()
    cursor.close()
    conn.close()